package com.light.modules.admin.system.controller;

import java.util.List;

import com.jfinal.aop.Duang;
import com.light.modules.admin.common.controller.AdminController;
import com.light.modules.admin.common.util.PasswordUtil;
import com.light.modules.admin.system.model.Menu;
import com.light.modules.admin.system.model.SysUser;
import com.light.modules.admin.system.service.LoginService;
import org.apache.commons.lang3.StringUtils;

import static com.light.common.ZcurdConst.*;

/**
 * 登录控制器
 *
 * @author:zhangdb
 * @date:2017/12/4
 */
public class LoginController extends AdminController {

    /**
     * 首页
     */
    public void index() {
        render("login.html");
    }

    /**
     * 登录操作
     */
    public void login() {
        LoginService loginService = Duang.duang(LoginService.class);
        List<SysUser> list = SysUser.me.findByMultiProperties(new String[]{"user_name", "password"},
                new Object[]{getPara("user_name"), PasswordUtil.encodePassword(getPara("password"))});
        if (list.size() > 0) {
            setSessionAttr(ADMIN_SESSIOIN_USER_KEY, list.get(0));
            //用户菜单
            setSessionAttr(ADMIN_MENULIST, loginService.getUserMenu(getSessionUser()));
            //页面权限
            setSessionAttr(ADMIN_NOAUTHURL, loginService.getNoAuthUrl());
            //按钮权限
            setSessionAttr(ADMIN_NOAUTHBTNURL, loginService.getNoAuthBtnUrl(getSessionUser()));
            //数据权限
            setSessionAttr(ADMIN_NOAUTHDATARULE, loginService.getNoAuthDatarule(getSessionUser()));
            if (StringUtils.equals(ADMIN_USERNAME,getSessionUser().get("user_name"))) {
                setSessionAttr(ADMIN_NOAUTHURL, null);
                setSessionAttr(ADMIN_NOAUTHBTNURL, null);
                setSessionAttr(ADMIN_NOAUTHDATARULE, null);
            }
            addOpLog("登陆系统");
            renderSuccess();
        } else {
            renderFailed("用户名或密码错误！");
        }
    }

    /**
     * 退出操作
     */
    public void getMenu() {
        //admin用户拥有所有页面
        if (StringUtils.equals(ADMIN_USERNAME,getSessionUser().get("user_name"))) {
            renderJson(Menu.me.findAll());
        } else {
            Object menuList = getSessionAttr(ADMIN_MENULIST);
            renderJson(menuList);
        }
    }

    public void logout() {
        addOpLog("退出系统");
        removeSessionAttr("sysUser");
        redirect(ADMINPATH +"/login");
    }
}
